<template>
  <el-container>
    <el-main>
      <el-form ref="orderForm" :model="form" :rules="rules" label-width="80px">
        <div style="width: 100%;display: flex;align-items: flex-end;border-bottom: 1px #eee solid;margin-bottom: 20px">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 0;">销售单</span>
        </div>
        <el-row type="flex" class="row-bg">
          <el-col :span="6">
            <el-form-item label="客户名称" prop="memberId">
              <div class="input_box">
                <span class="input_box_fz">{{memberName}}</span>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="销售日期">
              <el-date-picker
                style="width: 100%"
                v-model="form.orderDate"
                type="date"
                placeholder="选择日期">
              </el-date-picker>

            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属部门">
              <el-input v-model="officeName" suffix-icon="el-icon-arrow-down" @focus="dialogShow"/>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="销售门店">
              <el-select style="width: 100%" v-model="shopName" value-key="id" @change="changeShop" placeholder="请选择状态" filterable :filter-method="shopMethod">
                <el-option v-for="item in shops"  :key="item.id" :label="item.name" :value="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="6">
            <el-form-item label="订货方式">
              <el-select style="width: 100%" v-model="orderMethod" placeholder="请选择状态">
                <el-option label="线上订单" value="0"></el-option>
                <el-option label="人工报单" value="1"></el-option>
                <el-option label="门店销信" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="配送方式">
              <el-select style="width:100%" v-model="shippingMethod" placeholder="请选择状态">
                <el-option label="普通快递" value="0"></el-option>
                <el-option label="到店提货" value="1"></el-option>
                <el-option label="同城物流" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售人员">
              <el-select style="width: 100%" v-model="operatorName" filterable placeholder="请选择"
                         @change="selectSysEmployee">
                <el-option
                  v-for="item in sysEmployeeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="开票类型">
              <el-select style="width: 100%" v-model="taxType" placeholder="请选择状态">
                <el-option label="不开票" value="0"></el-option>
                <el-option label="增票" value="1"></el-option>
                <el-option label="普票" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row type="flex" class="row-bg">
          <el-col :span="11">
            <el-form-item label="详细地址" prop="address">
              <el-select style="width: 100%" v-model="form.address" value-key="id" filterable placeholder="请选择"
                         @change="selectReceiver">
                <el-option
                  v-for="item in receiverForm"
                  :key="item.id"
                  :label="item.address"
                  :value="item">
                </el-option>
                <el-option style="background-color: #f9f9f9;text-align: center;" key="*" label="底部隐藏块"
                           value="*"></el-option>
                <el-option style="background-color: #f9f9f9;text-align: center;position: absolute;bottom:0;width: 100%" key="#" label="--- 新增收货地址 ---"
                           value="#"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone"/>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="收货人" prop="consignee">
              <el-input v-model="form.consignee"/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row type="flex" class="row-bg">
          <el-col :span="11">
            <el-form-item label="买家留言">
              <el-input v-model="form.memo"/>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="product_header_name" style="">
          <span style="font-size: 18px;color:#409EFF;margin: 10px 10px;">商品明细</span>
        </div>
        <!--商品规格-->
        <el-table
          :data="productList"
          border
          show-summary
          stripe
          style="width: 100%">
          <el-table-column
            label="排序"
            type="index"
            width="50"
          >
          </el-table-column>
          <el-table-column
            label="商品名">
            <template slot-scope="{row}">
              <span>{{row.name}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="规格"
            max-width="300"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{row.spec}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="货号/条码"
            width="150"
          >
            <template slot-scope="{row}">
              <span>{{row.sn}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="单位"
            width="50"
            align="center"
          >
            <template slot-scope="{row}">
              <span>{{row.unit}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="数量"
            prop="quantity"
            align="center"
            width="70">
            <template slot-scope="{row}">
              <span>{{row.quantity}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="单价"
            width="70">
            <template slot-scope="{row}">
              <span>{{row.price}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="金额"
            width="70"
            align="right"
            prop="subTotal"
          >
          </el-table-column>
          <el-table-column
            label="优惠"
            width="70"
            align="right"
            prop="discount"
          >
          </el-table-column>
          <el-table-column
            label="实收"
            width="70"
            align="right"
            prop="amountPaid"
          >
          </el-table-column>
        </el-table>
        <div
          style="background-color: #EBEEF5;width: 100%;border-left: 1px solid #DCDFE6;border-right: 1px solid #DCDFE6;border-bottom: 1px solid #DCDFE6;display: flex;justify-content: space-between;padding: 10px;">
          <div style="display: flex;flex-direction: column">
            <div style="display:flex;align-items: center;justify-content: space-between;margin-bottom: 10px">
              <div style="display: flex;margin-right: 20px;align-items: center">
                <span style="font-size: 16px;color: #606266">运费金额：</span>
                <div style="width: 100px">
                  <span style="font-size: 16px;color: #606266">{{form.freight}}</span>
                </div>
              </div>
            </div>
            <div style="display: flex;align-items: center;justify-content: space-between">
              <div style="display: flex;margin-right: 20px;align-items: center">
                <span style="font-size: 16px;color: #606266">抹零金额：</span>
                <div style="width: 100px">
                  <el-input v-model="form.offsetAmount " @change="toCalculateClick"/>
                </div>
              </div>
            </div>
          </div>
          <div>
            <div style="margin-bottom: 10px">
              <span style="font-size: 16px;color: #606266">应收金额：{{form.amountPayable}}</span>
            </div>
            <div style="display: flex;align-items: center" v-for="item in form.paymentVo">
              <div>
                <span
                  style="font-size: 16px;color: #606266;display: block;width: 100%">{{item.paymentPluginName}}：</span>
              </div>
              <div class="payInput_Box"
                   style="padding-left: 10px;padding-right: 10px;padding-top: 5px;padding-bottom: 5px">
                <span class="input_box_fz">{{item.amount}}</span>
              </div>
            </div>
          </div>
        </div>
        <el-button type="primary" style="margin-top: 20px" :loading="clicked" @click="editClick('orderForm')">保存
        </el-button>
      </el-form>
      <el-dialog
        title="新增地址"
        :visible.sync="receiverVisible"
        width="950px"
        v-el-drag-dialog
        append-to-body
        :before-close="receiverClose">
        <div style="position: relative;height: 60vh;overflow: auto">
          <receiverAdd @orderReceiver="orderReceiver" pathType="0" :memberId="form.memberId"></receiverAdd>
        </div>
      </el-dialog>
    </el-main>
    <office-dialog ref="officeDialog" @confirm="dialogConfirm"/>
  </el-container>
</template>
<script>
  import {EventBus} from '@/api/eventBus'
  import {list as productList} from '@/api/product'
  import {list as shopList} from '@/api/shop'
  import {list as memberList} from '@/api/member'
  import {list as sysEmployeeList} from '@/api/sysEmployee'
  import {update, calculate, find} from '@/api/order'
  import utils from '../../utils/utils.js'
  import productAdd from '@/views/product/add'
  import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
  import productTable from './components/productList'
  import Distpicker from '@/components/Distpicker/Distpicker'
  import memberAdd from '@/views/member/add'
  import receiverAdd from '@/views/receiver/add'
  import OfficeDialog from '@/components/OfficeDialog'
  import {findBySn} from "../../api/product";
  import productRadio from './components/productRadio'
  import {list as receiverList} from '@/api/receiver'

  export default {
    directives: {elDragDialog},
    name: 'order-edit',
    data() {
      return {
        clicked: false, // 按钮防双击
        shopName:'',
        shops:[],
        form: {
          taxType: '0',
          shopId:'',
          id: '',
          memberId: '',
          orderDate: new Date(),
          operatorId: '',
          orderMethod: '0',
          shippingMethod: '0',
          officeId: '',
          areaId: 440000,
          areaName: '广东省广州市海珠区',
          address: '',
          memo: '',
          consignee: '',
          phone: '',
          freight: 0,
          amountPayable: 0,
          amountPaid: 0,
          paymentMethod: '0',
          subPrice: 0,
          subQuantity: 0,
          offsetAmount: 0,
          pointDiscount: 0,
          cardDiscount: 0,
          discount: 0,
          paymentVo: []
        },
        productList: [],
        query: {
          sn: ''
        },
        keyword: {
          sn: ''
        },
        listForm: [],
        tableIndex: '',
        procuctVisible: false,
        orderVisible: false,
        productType: 'order',
        chooseOrderName: '',
        memberName: '',
        memberList: [],
        memberVisible: false,
        memberType: 'add',
        sysEmployeeList: [],
        operatorName: '',
        officeName: '',
        rules: {
          memberId: [
            {required: true, message: '请选择客户', trigger: 'blur'},
          ],
          address: [
            {required: true, message: '收货地址不能为空', trigger: 'blur'}
          ],

        },
        queryType: false,
        findByList: [],
        receiverType: false,
        memberId: '',
        amount: '',
        receiverForm: [],
        receiverVisible: false,
        shippingMethod:'0',
        taxType:'0',
        orderMethod:'0'
      }
    },
    created() {
      var _this = this;
      this.loadSysEmployee()
      _this.form.id = this.$route.query.id;
      this.loadShop('')
      find(this.$route.query.id).then(response => {
        console.log(response);
        _this.form.memberId = response.data.order.memberId;
        _this.form.orderDate = response.data.order.orderDate;
        _this.form.operatorId = response.data.order.operatorId;
        _this.form.orderMethod = JSON.stringify(response.data.order.orderMethod)
        _this.orderMethod = JSON.stringify(response.data.order.orderMethod)
        _this.form.shippingMethod = JSON.stringify(response.data.order.shippingMethod)
        _this.shippingMethod = JSON.stringify(response.data.order.shippingMethod)
        _this.form.taxType = JSON.stringify(response.data.order.taxType)
        _this.taxType = JSON.stringify(response.data.order.taxType)
        _this.form.officeId = response.data.order.officeId;
        _this.form.memo = response.data.order.memo;
        _this.form.phone = response.data.order.phone;
        _this.form.consignee = response.data.order.consignee;
        _this.form.freight = response.data.order.freight;
        _this.form.amountPayable = response.data.order.amountPayable;
        _this.form.amountPaid = response.data.order.amountPaid;
        _this.form.subPrice = response.data.order.subPrice;
        _this.form.subQuantity = response.data.order.subQuantity;
        _this.form.address = response.data.order.address;
        _this.form.areaName = response.data.order.areaName;
        _this.form.areaId = response.data.order.areaId;
        _this.form.discount = response.data.order.discount;
        _this.form.offsetAmount = response.data.order.offsetAmount;
        _this.form = response.data.order;
        _this.memberName = response.data.memberName;
        _this.operatorName = response.data.operatorName;
        _this.officeName = response.data.officeName;
        _this.productList = response.data.order.itemList;
        // _this.calculateClick()
        _this.loadReceiver();
        console.log(_this.productList)
      }).catch(error => {
      })

    },
    components: {
      productAdd, productTable, Distpicker, memberAdd, OfficeDialog, productRadio, receiverAdd
    },
    filters: {
      watchOrderMethod(val) {
        if (val == 0) {
          return '线上订单'
        } else if (val == 1) {
          return '人工报单'
        } else if (val == 2) {
          return '门店销售'
        }
      },
      watchShippingMethod(val) {
        if (val == 0) {
          return '普通快递'
        } else if (val == 1) {
          return '到店提货'
        } else if (val == 2) {
          return '同城物流'
        }
      },
    },
    methods: {
      //  业务员
      loadSysEmployee() {
        var _this = this
        let params = new URLSearchParams();
        sysEmployeeList(params).then(response => {
          console.log(response);
          _this.sysEmployeeList = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      }
      ,
      //订单保存
      editClick(form) {
        const _this = this
        this.$refs[form].validate((valid) => {
          console.log(valid)
          if (valid) { // 校验表单
            _this.clicked = true
            _this.$delete(_this.form,'memberName')
            _this.$delete(_this.form,'memberMobile')
            update(_this.form).then(response => {
              console.log(response)
              _this.clicked = false
              EventBus.$emit('order-edit', response.data)
              _this.$store.dispatch('tagsView/delView', _this.$route).then(({visitedViews}) => {
                _this.$router.push({
                  path: '/order/view', query: {id: _this.form.id}
                })
              })// 关闭当前tab回到列表
            }).catch(error => {
              _this.clicked = false
            })
          } else {
            return false
          }
        })
      },
      shopMethod(data){
        this.loadShop(data)
      },
      changeShop(data){
        this.shopName=data.name
        this.form.shopId=data.id
      },
      loadShop(query){
        let params=new URLSearchParams()
        params.append('name',query)
        shopList(params).then(res=>{
          this.shops=res.data.data
        })
      },
      selectSysEmployee(data) {
        this.form.operatorId = data
      },

      //  销售公司
      dialogShow() {
        console.log('点击了');
        this.$refs.officeDialog.show()
      }
      ,
      dialogConfirm(val) {
        this.form.officeId = val.id;
        this.officeName = val.name
      },
      //  地址选择
      // loadReceiver() {
      //   var _this = this
      //   this.memberId = this.form.memberId
      //   this.receiverType = true
      //   console.log(this.memberId)
      // },

      //  计算
      calculateClick() {
        var _this = this;
        // let itemList = [];
        // _this.productList.forEach(function (item) {
        //   var goodsDetails = {
        //     productId: item.productId,
        //     name: item.name,
        //     sn: item.sn,
        //     price: item.price,
        //     quantity: item.quantity,
        //     spec: item.spec,
        //     cost: item.cost
        //   };
        //   itemList.push(goodsDetails)
        // });
        // let formData = {
        //   id:_this.form.id,
        //   memberId: _this.form.memberId,
        //   createDate: _this.form.createDate,
        //   operatorId: _this.form.operatorId,
        //   orderMethod:_this.form.orderMethod,
        //   shippingMethod: _this.form.shippingMethod,
        //   officeId: _this.form.officeId,
        //   areaName: _this.form.areaName,
        //   address: _this.form.address,
        //   areaId: _this.form.areaId,
        //   memo: _this.form.memo,
        //   phone:_this.form.phone,
        //   consignee:_this.form.consignee,
        //   offsetAmount:_this.form.offsetAmount,
        //   itemList: itemList
        // };
        //TODO
        /* var form = eval(_this.form)
         var vform = delete eval(form).memberName
          vform = delete eval(form).memberMobile
         console.log(vform)
         console.log(form)
         calculate(form).then(response => {
           console.log(response)
           if (!utils.isNull(response.data.freight)) {
             _this.form.freight = response.data.freight
           }
           if (!utils.isNull(response.data.offsetAmount)) {
             _this.form.offsetAmount = response.data.order.offsetAmount
           }
           if (!utils.isNull(response.data.pointDiscount)) {
             _this.form.pointDiscount = response.data.pointDiscount
           }
           _this.form.amountPayable = response.data.amount
           _this.form.paymentVo = response.data.order.paymentVo
         }).catch(error => {

         })*/
      },
      toCalculateClick() {
        var _this = this
        _this.calculateClick()
      },
      loadReceiver() {
        var _this = this
        let params = new URLSearchParams();
        params.append('pageNum', 1);
        params.append('pageSize', 100);
        params.append('memberId', _this.form.memberId);
        receiverList(params).then(response => {
          console.log(response)
          _this.receiverForm = response.data.data
          if (utils.isNull(_this.form.address)){
            _this.form.address = response.data.data[0].address
            _this.form.areaName = response.data.data[0].areaName
            _this.form.areaId = response.data.data[0].areaId;
            _this.form.consignee = response.data.data[0].consignee;
            _this.form.phone = response.data.data[0].phone
          }
        }).catch(error => {
          console.log('error!!')
        });
      },
      selectReceiver(data) {
        console.log(data)
        var _this = this
        if (utils.isNull(_this.form.memberId)) {
          _this.$message({
            message: '请先选择客户',
            type: 'warning'
          });
          this.form.address = ''
          return;
        }
        if (data == '#') {
          _this.receiverVisible = true;
          this.form.address = ''
        } else {
          _this.form.address = data.address
          _this.form.areaName = data.areaName
          _this.form.areaId = data.areaId;
          _this.form.consignee = data.consignee;
          _this.form.phone = data.phone
        }
      },
      receiverClose() {
        this.receiverVisible = false;
      },
      orderReceiver(data) {
        var _this = this
        _this.receiverForm.push(data.data)
        _this.form.address = data.data.address
        _this.form.areaName = data.data.areaName
        _this.form.areaId = data.data.areaId;
        _this.form.consignee = data.data.consignee;
        _this.form.phone = data.data.phone;
        _this.receiverClose()
      },
    }
  }
</script>

<style scoped>
  /deep/ .el-dialog__header {
    border-bottom: 1px solid #CCCCCC;
  }

  .product_header_name {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-left: 5px #409EFF solid;
    margin-bottom: 20px;
    background-color: #f2f2f2;
  }

  .input_box {
    width: 100%;
    height: 100%;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    padding-left: 15px;
    padding-right: 15px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .input_box_fz {
    color: #909399;
  }

  .payInput_Box {
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    padding-left: 15px;
    padding-right: 15px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
